<!-- 我的收藏项目 -->
<template>
  <div class="list-box my-scrollbar">
    <activity-card
      v-for="(item, index) in dataList"
      :key="index"
      card-width="590px"
      :data="item"
      @on-click-card="handleClickCard(item as Record)"
      @onClickParticipation="onClickParticipation"
    />
  </div>
  <my-infinite-loading :empty="dataList?.length === 0" :identifier="identifier" @infinite="loadData" />

  <participation-modal ref="participationModalRef" @success="participationSuccess" />
</template>

<script lang="ts" setup>
  import { ref } from 'vue'

  import { ActivityCardData } from '@/components/ActivityCard/index.vue'
  import { hitContestApi } from '@/services/api'
  import ParticipationModal from '@/views/customer/hit-contest/detail/components/ParticipationModal.vue'
  import { statusMap } from '@/views/customer/hit-contest/options'
  import { Record } from '@/views/customer/hit-contest/types'

  import { ProPageForm } from '../../types'

  const pageForm = ref<ProPageForm>({
    columns: 'createTime',
    order: 'desc',
    offset: 1,
    limit: 8
  })
  const identifier = ref<number>(1)

  const dataList = ref<ActivityCardData[]>([])

  const loadData = async ($state: any) => {
    try {
      const {
        data: { records }
      } = await hitContestApi.myList(pageForm.value)

      if (records.length < pageForm.value.limit) {
        $state.complete()
      } else {
        pageForm.value.offset++
        $state.loaded()
      }

      const list: ActivityCardData[] = records.map((item: Record) => {
        return {
          id: item.id,
          title: item.name,
          describe: item.description,
          date: `${item.beginTime} - ${item.endTime}`,
          status: statusMap[item.status],
          statusText: item.status,
          label: item.labels || [],
          userNum: item.participantNum,
          isJoin: item.joinStatus
        }
      })
      dataList.value.push(...list)
    } catch (error) {
      $state.error()
    }
  }

  /* 立即参与 */
  const participationModalRef = ref<InstanceType<typeof ParticipationModal>>()
  const onClickParticipation = (data: ActivityCardData) => {
    participationModalRef.value?.open({ id: data.id })
  }
  const participationSuccess = () => {
    dataList.value = []
    pageForm.value.offset = 1
    window.scrollTo({
      top: 0
    })
    identifier.value = Date.now()
  }

  /*----------------------------------------- 详情 --------------------------------*/
  const handleClickCard = (item: Record) => {
    window.open(`/hit-contest/detail/${item.id}`)
  }

  // const refreshDataList = () => {
  //   pageForm.value.offset = 1
  //   pageForm.value.limit = 45
  //   dataList.value = []
  //   identifier.value = Date.now()
  // }
</script>

<style lang="less" scoped>
  .list-box {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    flex: 1;
    gap: 20px 20px;
  }
</style>
